<template>
  <div class="container">
    <div class="layui-container fly-marginTop">
      <div class="fly-panel fly-panel-user" pad20>
        <div class="layui-tab layui-tab-brief" lay-filter="user">
          <ul class="layui-tab-title">
            <li class="layui-this">登入</li>
            <li><router-link :to="{name: 'Reg'}">注册</router-link></li>
          </ul>
          <div class="layui-form layui-tab-content" id="LAY_ucm" style="padding: 20px 0;">
            <div class="layui-tab-item layui-show">
              <div class="layui-form layui-form-pane">
                <form method="post">
                  <ValidationObserver ref="observer" v-slot="{ invalid }">
                    <div class="layui-form-item">
                      <label for="L_email" class="layui-form-label">用户名</label>
                      <ValidationProvider rules="required|email" v-slot="{errors}">
                        <div class="layui-input-inline">
                          <input type="text" id="L_email" name="email" autocomplete="off" class="layui-input" placeholder="请输入用户名" v-model="username">
                        </div>
                        <div class="layui-form-mid">
                          <span style="color: #c00;">{{errors[0]}}</span>
                        </div>
                      </ValidationProvider>
                    </div>
                    <div class="layui-form-item">
                      <label for="L_pass" class="layui-form-label">密码</label>
                      <ValidationProvider rules="required|min:6" v-slot="{errors}">
                        <div class="layui-input-inline">
                          <input type="password" id="L_pass" name="password" autocomplete="off" class="layui-input" placeholder="请输入密码" v-model="password">
                        </div>
                        <div class="layui-form-mid">
                          <span style="color: #c00;">{{errors[0]}}</span>
                        </div>
                      </ValidationProvider>
                    </div>
                    <ValidationProvider rules="required|length:4" v-slot="{errors}" ref="codeField">
                      <div class="layui-form-item">
                        <label for="L_vercode" class="layui-form-label">验证码</label>
                        <div class="layui-input-inline">
                          <input type="text" id="L_vercode" name="code" placeholder="请输入验证码" autocomplete="off" class="layui-input" v-model="code">
                        </div>
                        <div @click="_getCode">
                          <span v-html="svg" class="svg"></span>
                        </div>
                      </div>
                      <div class="layui-form-mid">
                        <span style="color: #c00;">{{errors[0]}}</span>
                      </div>
                    </ValidationProvider>
                    <div class="layui-form-item">
                      <button class="layui-btn" lay-filter="*" lay-submit type="button" @click="() => { if (invalid) {return} else {submit()} }">立即登录</button>
                      <span style="padding-left:20px;">
                        <router-link :to="{name: 'Forget'}">忘记密码？</router-link>
                      </span>
                    </div>
                  </ValidationObserver>
                  <div class="layui-form-item fly-form-app">
                    <span>或者使用社交账号登入</span>
                    <a href="" onclick="layer.msg('正在通过QQ登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-qq" title="QQ登入"></a>
                    <a href="" onclick="layer.msg('正在通过微博登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-weibo" title="微博登入"></a>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { loginSubmit } from '@/api/login.js';
import { ValidationProvider, ValidationObserver } from 'vee-validate';
import codeMix from '@/mixin/codeMixin';

export default {
  name: 'Login',
  components: {
    ValidationProvider,
    ValidationObserver
  },
  mixins: [codeMix],
  data () {
    return {
      username: '',
      password: '',
      svg: '',
      code: ''
    };
  },
  methods: {
    async submit () {
      const isValidate = await this.$refs.observer.validate();
      if (isValidate) {
        let data = {
          username: this.username,
          password: this.password,
          sid: this.$store.state.sid,
          code: this.code
        };
        loginSubmit(data).then((res) => {
          // 请求发送成功则清空表单
          // console.log(res);
          if (res.code === 200) {
            res.data.email = this.username;
            this.username = '';
            this.password = '';
            this.code = '';
            requestAnimationFrame(() => {
              if (this.$refs.observer) {
                this.$refs.observer.reset();
              }
            });
            this.$store.commit('setIsLogin', true);
            this.$store.commit('setToken', res.token);
            this.$store.commit('setUserInfo', res.data);
            localStorage.setItem('token', res.token);
            localStorage.setItem('userInfo', JSON.stringify(res.data));
            this.$router.push('/index');
          }
          // 服务器返回错误的处理
          if (res.code === 403) {
            // 在code验证表单上设置错误
            this.$refs.codeField.setErrors([res.msg]);
          }
        })
          .catch(err => {
            // 通过err.response获取错误请求的响应信息
            if (err.response.data.code === 403) {
              this.$alert(err.response.data.msg);
            } else {
              this.$alert('服务器出错了');
            }
          });
      }
    }
  }
};
</script>
<style scoped lang="scss">
.svg {
  position: relative;
  top: -6px;
}
</style>
